package com.examination.client.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.examination.client.annotation.PassToken;
import com.examination.client.config.WechatAccountConfig;
import com.examination.client.domian.dto.PushMessageDTO;
import com.examination.client.domian.dto.WechatOpenIdDTO;
import com.examination.client.domian.vo.WechatConfigVO;
import com.examination.client.entity.WechatUser;
import com.examination.client.exception.BusinessException;
import com.examination.client.service.IWechatUserService;
import com.examination.client.util.JsonUtils;
import com.examination.client.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.lang.invoke.LambdaConversionException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Objects;

/**
 * @author: XiaoDong
 * @date: 2021-10-27 13:07
 * @description:
 */

@RestController
@RequestMapping("/wechat")
@Slf4j
@Api(tags = "微信公众号")
@CrossOrigin(origins = "*")
public class WechatController {

    @Autowired
    private WxMpService wxMpService;

    @Autowired
    private WechatAccountConfig wechatAccountConfig;
    @Autowired
    IWechatUserService wechatUserService;


    @PassToken
    @GetMapping("/config")
    @ApiOperation("微信公众号配置")
    public Result<WechatConfigVO> config(){
        WechatConfigVO wechatConfigVO = new WechatConfigVO();
        wechatConfigVO.setAppId(wechatAccountConfig.getAppId());
        wechatConfigVO.setAppSecret(wechatAccountConfig.getAppSecret());
        wechatConfigVO.setAppId(wechatAccountConfig.getAppId());
        wechatConfigVO.setAppSecret(wechatAccountConfig.getAppSecret());
        return Result.success(wechatConfigVO);
    }

    @PassToken
    @PostMapping("/user/phone")
    @ApiOperation("h获取用户手机号")
    public Result<WechatUser> getUserPhone(@RequestBody  @Validated WechatOpenIdDTO wechatOpenIdDTO) throws Exception {
        //log.info("微信网页授权 参数={}", JsonUtils.toJson(wechatOpenIdDTO));

        WxMpOAuth2AccessToken wxMpOAuth2AccessToken;
        try {
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(wechatOpenIdDTO.getCode());
        } catch (Exception e) {
            //log.info("微信网页授权{}", e);
            return Result.fail(e.getMessage());
        }
        String openId = wxMpOAuth2AccessToken.getOpenId();
        if(StringUtils.isBlank(openId)){
            return Result.fail("获取openId 为空");
        }
        //log.info("微信网页授权openId={}", openId);
        LambdaQueryWrapper<WechatUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WechatUser::getOpenId,openId);

        WechatUser wechatUser = wechatUserService.getOne(queryWrapper);
        if(Objects.isNull(wechatUser)){
            wechatUser = new WechatUser();
            wechatUser.setOpenId(openId);
            wechatUser.setCreateTime(new Date());
            wechatUserService.save(wechatUser);
        }
        return Result.success(wechatUser);

    }

    @PassToken
    @PostMapping("/save")
    @ApiOperation("保存用户微信信息")
    public Result<Boolean> save(@RequestBody  @Validated WechatOpenIdDTO WechatOpenIdDTO) throws Exception {
        //log.info("【微信网页授权】参数={}", JsonUtils.toJson(WechatOpenIdDTO));
        String openId = "";
        if (StringUtils.isBlank(WechatOpenIdDTO.getOpenId())) {
            WxMpOAuth2AccessToken wxMpOAuth2AccessToken;
            try {
                wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(WechatOpenIdDTO.getCode());
            } catch (Exception e) {
                //log.info("【微信网页授权】{}", e);
                return Result.fail(e.getMessage());
            }
            openId = wxMpOAuth2AccessToken.getOpenId();
            if (StringUtils.isBlank(openId)) {
                return Result.fail("获取openId 为空");
            }
            //log.info("【微信网页授权】openId={}", openId);
        } else {
            openId = WechatOpenIdDTO.getOpenId();
        }

        WechatUser wechatUser = new WechatUser();
        wechatUser.setUserPhone(WechatOpenIdDTO.getUserPhone());
        wechatUser.setOpenId(openId);
        wechatUser.setCreateTime(new Date());
        wechatUserService.saveOrUpdate(wechatUser, new QueryWrapper<WechatUser>().lambda().eq(WechatUser::getOpenId, openId));
        return Result.success(true);

    }

    @PostMapping("/message")
    @ApiOperation("推送消息")
    public Result<Boolean> message() throws Exception {
        return Result.success(wechatUserService.message());
    }
}
